package net.kong.yumo.assa.hasor.udf;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;


import net.hasor.core.Inject;
import net.kong.yumo.assa.hasor.config.transactionTemplateHasor;
 

public class jtaCrudUtil {

	private static Logger logger = LoggerFactory.getLogger(jtaCrudUtil.class);

	@Inject()
	transactionTemplateHasor tth;
	/**
	 * 多数据源
	 * @param updateSqls
	 * @param list
	 * @return
	 * @throws Throwable
	 */
	public Map<String,Object> jtaUpdateSqlsParam(String[] dataSourcesNames,String[] updateSqls,List<Map<String, Object>> list ) throws Throwable {
		
		Map<String,Object> re= new HashMap();
    	
    	if(!(dataSourcesNames.length==updateSqls.length && updateSqls.length==list.size())) {
        	re.put("code", -1);
    		re.put("msg", "参数长度错误");
    		return re;
    		}
		List<Integer> ints= new ArrayList(); 
		NamedParameterJdbcTemplate j1=tth.getJta1Sys();
		NamedParameterJdbcTemplate j2=tth.getJta2dagl();
		TransactionTemplate tt=tth.getJtatt();
		//设置事务传播属性
//		tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		// 设置事务的隔离级别,设置为读已提交（默认是ISOLATION_DEFAULT:使用的是底层数据库的默认的隔离级别）
//		tt.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
		// 设置是否只读，默认是false
//		tt.setReadOnly(true);
		// 默认使用的是数据库底层的默认的事务的超时时间
//		tt.setTimeout(30000);
		tt.execute(new TransactionCallback<Object>() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				// TODO Auto-generated method stub
				int a;
				int l=list.size();
				String dsn;
				 try {
		        	 for(int index=0;index<l;index++) {
		        		dsn= dataSourcesNames[index];
	        			logger.info("----------dsn:"+dsn);
	        			logger.info("----------Sql:"+updateSqls[index]);
	        			logger.info("-----------param:"+list.get(index));
		        		if ( "jta1sys".equals(dsn)) {
			     			a=j1.update(updateSqls[index],list.get(index));
			     			ints.add(a);
		        		}
		        		if ( "jta2dagl".equals(dsn)) {
			     			a=j2.update(updateSqls[index],list.get(index));
			     			ints.add(a);
		        		}
		     		 }
		        	 re.put("code", 1);
		            return null;
		        } catch (Exception e) {
		            //回滚
		        	logger.info("------Exception:"+e.getMessage());
		        	re.put("code", -1);
		        	re.put("msg", e.getMessage());
		        	status.setRollbackOnly();
		            return null;
		        }
			}			 			
		});
		re.put("data", ints);
    	re.put("msg", "success");
		return re;
	}
	
}
